//
//  AppStorePayment.m
//  Unity-iPhone
//
//  Created by zhang fenglin on 13-9-17.
//
//

#import "AppStorePayment.h"
#import "CJSONDeserializer.h"
#import "AlertContent.h"
#import "LoadingLayer.h"

static NSString* gameobjectName = NULL;
static AppStorePayment *singleton = NULL;

//#define DM_PUBLISHER_ID @"56OJyM1ouMGoULfJaL"
#define DM_PUBLISHER_ID @"56OJwnZouNLH2Nx7ad"
//#define DM_PLACEMENT_ID @"16TLwebvAchkANUH_krQ7vOz"
#define DM_PLACEMENT_ID @"16TLuONvApfeHNUf8Pgxtfos"
@interface AppStorePayment ()
{
    CGPoint origin;
}
@end



@implementation AppStorePayment
@synthesize userName;
@synthesize gameId;
@synthesize gatewayId;
@synthesize callbackUrl;

void sendMsg2Unity(NSString* func, NSString* msg)
{
    UnitySendMessage([gameobjectName UTF8String], [func UTF8String], [msg UTF8String]);
}

+(AppStorePayment*)sharedInstance
{
    return singleton == NULL ? (singleton = [[self alloc] init]) : singleton;
}

-(id)init
{
    if ((self = [super init]))
    {
        m_ProductList = [[NSMutableArray alloc] init];
        isTasking = YES;
        isPaying = NO;
    }
    return self;
}

-(void)dealloc
{
    [m_ProductList release];
    [super dealloc];
}

-(void)setUserInfo:(NSString*)username gameId:(NSString*)gameid gatewayId:(NSString*)gatewayid callbackUrl:(NSString*) callbackurl
{
    self.userName = username;
    self.gameId = gameid;
    self.gatewayId = gatewayid;
    self.callbackUrl = callbackurl;
    //    NSString* json = [NSString stringWithFormat:@"{\"userName\":\"%@\",\"gameId\":\"%@\",\"gatewayId\":\"%@\",\"productId\":\"%@\",\"transactionReceipt\":\"%@\",\"time\":\"%@\"}",username,gameid, gatewayid,@"productid",@"transactionReceipt",[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]]];
    //    NSLog(@"json is : %@", json);
    
    
    //    NSLog(@"userName    : %@\n", userName);
    //    NSLog(@"gameId      : %@\n", gameId);
    //    NSLog(@"gatewayId   : %@\n", gatewayId);
    //    NSLog(@"callbackUrl : %@\n", callbackUrl);
}

-(void)setAlertMessage:(NSString*)key andContent:(NSString*)content
{
    [[AlertContent sharedInstance] addKey:key andObject:content];
    //    NSLog(@"%@ = %@", key, content);
    //    NSLog(@"allkeys : %@", [[AlertContent sharedInstance] allMsgKeys]);
}

#pragma mark 添加appstore购买服务
-(void)addAppstoreObserver
{
    if ([SKPaymentQueue canMakePayments])
    {
        [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        NSLog(@"suport payment server");
    }
    else
    {
        NSLog(@"not suport payment server !!!");
    }
}

-(void)appstoreInitProductList:(NSString*) productList
{
    NSArray* list = [productList componentsSeparatedByString:@"#"];
    NSSet* set = [NSSet setWithArray:list];
    SKProductsRequest* request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
    request.delegate = self;
    [request start];
    //    NSLog(@"list is : %@", list );
}

-(void)buyWithProductId:(NSString*)productId
{
    if (isPaying)
    {
        NSLog(@"is paying now ......");
        return;
    }
    if (isTasking || [m_ProductList count] == 0)
    {
        [self messagePrompt:[[AlertContent sharedInstance] getObjectForKey:@"noproduct"]];
        return;
    }
    //    NSLog(@"payment productid is : %@", productId);
    if (productId == NULL || ![m_ProductList containsObject:productId])
    {
        [self messagePrompt:[[AlertContent sharedInstance] getObjectForKey:@"invalidproduct"]];
        return;
    }
    
    if ([[[SKPaymentQueue defaultQueue] transactions] count] > 0)
    {
        [self messagePrompt:[[AlertContent sharedInstance] getObjectForKey:@"isTasking"]];
        for (SKPaymentTransaction* transaction in [[SKPaymentQueue defaultQueue] transactions])
        {
            [self completeTransaction:transaction];
        }
        return;
    }
    isPaying = YES;
    SKPayment* payment = [SKPayment paymentWithProductIdentifier:productId];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
    [[LoadingLayer sharedInstance] startLoading];
}

#pragma mark appstore购买服务回调
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    for (SKPaymentTransaction* transaction in transactions)
    {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                //                NSLog(@"SKPaymentTransactionStatePurchasing");
                break;
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                //                NSLog(@"SKPaymentTransactionStatePurchased");
                break;
            case SKPaymentTransactionStateRestored:
                //                NSLog(@"SKPaymentTransactionStateRestored");
                break;
            case SKPaymentTransactionStateFailed:
                if(transaction.transactionState == 0 ||
                   transaction.transactionState == 2)
                {
                    [self transactionFailed:transaction];
                }
                else
                {
                    [self completeTransaction:transaction];
                }
                //                NSLog(@"SKPaymentTransactionStateFailed");
                break;
            default:
                break;
        }
    }
}

-(void)completeTransaction:(SKPaymentTransaction*) transaction
{
    //    NSLog(@"completeTransaction : %@", transaction.payment.productIdentifier);
    URLConnection* conn = [[URLConnection alloc] init];
    [conn setTarget:self];
    [conn sendRequestToServer:self.userName gameId:self.gameId gatewayId:self.gatewayId callbackUrl:self.callbackUrl Transaction:transaction];
    [conn release];
}

-(void)transactionFailed:(SKPaymentTransaction*) transaction
{
    //    NSLog(@"transactionFailed : %@", transaction.payment.productIdentifier);
    [[LoadingLayer sharedInstance] stopLoading];
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    isPaying = NO;
}

#pragma mark 获取产品列表的回调
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    //    NSLog(@"product list : %@", response.products);
    for (SKProduct* product in response.products)
    {
        if (![m_ProductList containsObject:product.productIdentifier])
        {
            [m_ProductList addObject:product.productIdentifier];
        }
    }
    isTasking = NO;
    //    NSLog(@"product list is : %@", m_ProductList);
}

- (void)requestDidFinish:(SKRequest *)request
{
    //    NSLog(@"requestDidFinish : %@", request);
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
    //    NSString* msg = [error localizedDescription];
    //    [self messagePrompt:msg];
    [self addAppstoreObserver];
}

-(void)paymentFinish:(SKPaymentTransaction *)transaction
{
   // NSLog(@"pid :: %@",transaction.payment.productIdentifier);
    //NSLog(@"transactionIdentifier :: %@",transaction.transactionIdentifier);
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    isPaying = NO;
}

#pragma mark 处理支付完成的结果回调
-(void)paymentFinish:(SKPaymentTransaction *)transaction data:(NSData *)data
{
    [[LoadingLayer sharedInstance] stopLoading];
    NSError* error = nil;
    NSDictionary* dic = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];

   // NSLog(@"dictionary is : %@", dic);
    //    NSString* code = [dic objectForKey:@"code"];
    NSString* status = [dic objectForKey:@"status"];
    if ([status compare:@"ok"] == NSOrderedSame)
    {
        NSLog(@"payment success");
        NSString* productid = transaction.payment.productIdentifier;
       // NSLog(@"pid :: %@",productid);
       // NSLog(@"transactionIdentifier :: %@",transaction.transactionIdentifier);
        sendMsg2Unity(@"onPayFinish", productid);
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        [self messagePrompt:[[AlertContent sharedInstance] getObjectForKey:@"transsuccess"]];
    }
    else
    {
        NSLog(@"payment failure");
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        [self messagePrompt:[[AlertContent sharedInstance] getObjectForKey:@"transfailed"]];
    }
    isPaying = NO;
    //    NSString* result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    ////    NSLog(@"paymentFinish result : %@ , %@",code, status);
    //    [result release];
    
}

-(void)PaymentFailed
{
    [[LoadingLayer sharedInstance] stopLoading];
    [self messagePrompt:[[AlertContent sharedInstance] getObjectForKey:@"transfailed"]];
    isPaying = NO;
}

-(void)TestGame
{
    URLConnection* conn = [[URLConnection alloc] init];
    [conn setTarget:self];
    [conn sendRequestToServer:self.userName gameId:self.gameId gatewayId:self.gatewayId callbackUrl:self.callbackUrl Transaction:nil];
    [conn release];
}

-(void)finishAll
{
    for (SKPaymentTransaction* tran in [[SKPaymentQueue defaultQueue] transactions])
    {
        [[SKPaymentQueue defaultQueue] finishTransaction:tran];
    }
}

-(void)messagePrompt:(NSString*)msg
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:self cancelButtonTitle:[[AlertContent sharedInstance] getObjectForKey:@"comfirm"] otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
}
- (void)viewDidDisappear:(BOOL)animated
{
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    
}

@end

#if defined(__cplusplus)
extern "C" {
#endif
    
    NSString* CreateString(const char* str){
        if (str)
            return [NSString stringWithUTF8String:str];
        else {
            return [NSString stringWithUTF8String:""];
        }
    }
    
	void setMessageObjName(const char* objName)
    {
        if ([gameobjectName retainCount] > 0)
            [gameobjectName release];
        gameobjectName = [CreateString(objName) retain];
    }
    
    NSDictionary* JsonToDictionary(const char *str)
    {
        NSLog(@"JsonToDictionary str = %s",str);
        
        NSString* jsonStr = CreateString(str);
        NSError* error = nil;
        if(jsonStr.length>0)
        {
            NSData* jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary* jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
            if(error == nil)
            {
                return  jsonDic;
            }
        }
        
        return nil;
    }
    
    //void lksdkInit(const char* appid, const char* appkey, const char* serverid, const char* cpid, const char* gameid)
    void lksdkInit(const char* json)
    {
        sendMsg2Unity(@"onListFinish", @"onListFinish");
    }
	
    void lksdkPayment(const char* productId, const char* serverid, const char* cooOrderSerial,const char* needPayCoins,const char* customInfo, const char* roleName, const char* roleId, const char* zoneId,const char* json)
	{
        NSLog(@"lksdkPayment begin");
        [[AppStorePayment sharedInstance] buyWithProductId:CreateString(productId)];
    }
    void U3dInitProductList(const char* product)
    {
        NSLog(@"U3dInitProductList begin");
        [[AppStorePayment sharedInstance] appstoreInitProductList:CreateString(product)];
    }
    
    void AddObserver()
    {
        [[AppStorePayment sharedInstance] addAppstoreObserver];
    }
	
    void setAlertInfoWithKeyAndMessage(const char* key, const char* message)
    {
        [[AppStorePayment sharedInstance] setAlertMessage:CreateString(key) andContent:CreateString(message)];
    }
    
    void setGameUserInfo(const char* username, const char* gameid, const char* gatewayid, const char* callbackurl)
    {
        [[AppStorePayment sharedInstance] setUserInfo:CreateString(username) gameId:CreateString(gameid) gatewayId:CreateString(gatewayid) callbackUrl:CreateString(callbackurl)];
    }
    
    void TestGame()
    {
        [[AppStorePayment sharedInstance] TestGame];
    }
    
    void FinishAll()
    {
        [[AppStorePayment sharedInstance] finishAll];
    }
#pragma mark Unuse in apple sdk
    void lksdkLogin(const char* json)
    {

    }
    
    void lksdkUserCenter(const char* json)
    {

    }

    void lksdkLogout(const char* json)
    {

    }

    void lksdkShowToolBar()
    {

    }

    void lksdkHideToolBar()
    {

    }

    void lksdkGamePause()
    {

    }
    
    void lksdkUserFeedback()
    {
        
    }
    
    void lksdkEnterBBS(const char* json)
    {
        
    }
    
    //-----------------------
    void lksdkRegister(const char *json)
    {
        
    }
    
    void lksdkEnterGame(const char *serverId,const char *extJson)
    {
        
    }
    
    void lksdkCreateRole(const char *serverId,const char *extJson)
    {
        
    }
    
    void lksdkInitServerId(const char *serverid)
    {
        
    }
    
    void lksdkPrintDebugLog(const char *message)
    {
        NSLog(@"Unity::%s",message);
    }
    
    void lksdkOnUserLevel(const char *roleLevel)
    {
        
    }
    
    void lksdkInitIAP(const char *json)
    {
        
    }
    
    void lksdkPostingStory(const char *filePath)
    {
        
    }
    
    void lksdkFriendsList()
    {
        
    }
    
    void lksdkSendMessage(const char *fId,const char *msg)
    {
        
    }
    
    void lksdkInviteFriend(const char *json)
    {
        
    }
    
    void lksdkRegistrationBind(const char *json)
    {
        
    }

#if defined(__cplusplus)
}
#endif
